package com.xdz.service.impl;

import com.xdz.client.CouponSpuboundClient;
import com.xdz.entity.vo.spu.Bounds;
import com.xdz.entity.vo.spu.SpuSaveVo;
import com.xdz.service.*;
import com.xdz.to.SpuBoundsTo;
import com.xdz.utils.PageUtils;
import com.xdz.utils.Query;
import com.xdz.utils.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.xdz.dao.SpuInfoDao;
import com.xdz.entity.SpuInfoEntity;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private CouponSpuboundClient couponSpuboundClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void saveSpuInfo(SpuSaveVo spuInfo) {
        // 保存基本信息
        Long spuId = this.saveSpu(spuInfo);
        // 保存描述图集
        spuInfoDescService.saveDesc(spuInfo.getDecript(), spuId);
        // 保存商品图集
        spuImagesService.saveImages(spuInfo.getImages(), spuId);
        // 保存属性信息
        productAttrValueService.saveSpuAttr(spuInfo.getBaseAttrs(), spuId);
        // 保存sku信息
        skuInfoService.saveSkuInfo(spuInfo.getSkus(), spuInfo, spuId);
        // 保存积分信息
        SpuBoundsTo saveBounds = new SpuBoundsTo();
        Bounds spuBounds = spuInfo.getBounds();
        saveBounds.setSpuId(spuId);
        saveBounds.setBuyBounds(spuBounds.getBuyBounds());
        saveBounds.setGrowBounds(spuBounds.getGrowBounds());
        R save = couponSpuboundClient.save(saveBounds);
        if (save.getCode() != 0) {
            log.error("保存spus时保存积分信息失败");
        }
    }

    @Override
    public Long saveSpu(SpuSaveVo spuInfo) {
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuInfoEntity, spuInfo);
        this.save(spuInfoEntity);
        return spuInfoEntity.getId();
    }

}